package com.daka.service.impl;

import com.daka.entity.WelfareItem;
import com.daka.service.FileUtil;
import com.daka.tools.poi.ExcelReader;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author beliveli on 2016/3/31 0031.
 */
@Service("fileUtil")
@SuppressWarnings("unused")
public class FileUtilImpl implements FileUtil {

    public File uploadFile(MultipartFile file, String patch) throws IOException {

        String randomName = RandomStringUtils.randomAlphabetic(8);
        String filename = randomName + "." + FilenameUtils.getExtension(file.getOriginalFilename());

        File filePatch = new File(patch);
        if(!filePatch.exists()){
            //noinspection ResultOfMethodCallIgnored
            filePatch.mkdirs();
        }
        File dest = new File(patch, filename);
        file.transferTo(dest);

        return dest;
    }

    public List<WelfareItem> readExcelFile(File excelFile) throws Exception {
        List<WelfareItem> welfareItemList = new ArrayList<WelfareItem>();

        ExcelReader er = new ExcelReader(excelFile);
        er.BeginRead();
        er.initRange();

        while (er.hasNext()) {
            String[] col = er.ReadNext();
            WelfareItem welfareItem = new WelfareItem();
            welfareItem.setCode(col[0]);
            welfareItem.setWelfareId((long) Double.parseDouble(col[1]));
            welfareItemList.add(welfareItem);
        }
        return welfareItemList;
    }
}

